package com.zzyl.framework.aspectj;

import com.alibaba.fastjson2.JSON;
import com.zzyl.common.annotation.AddCache;
import com.zzyl.common.annotation.DeleteCache;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 添加缓存，删除缓存切面
 */
@Component
@Aspect
public class RedisAspect {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Around("@annotation(addCache)")
    public Object addCache(ProceedingJoinPoint joinPoint, AddCache addCache) throws Throwable {

        /*
        先去缓存中查找值，如果值不存在，
        则去查询数据库，如何将值返回并添加缓存
         */

        //1.查询缓存
        Object value = redisTemplate.opsForValue().get(addCache.key());
        //2.判断缓存是否存在
        if (ObjectUtils.isNotEmpty(value)) {
            return value;
        }
        //3.执行目标方法，查询数据库，并返回数据
        value = joinPoint.proceed();
        //4.添加缓存
        redisTemplate.opsForValue().set(addCache.key(),value);
        //返回数据
        return value;
    }


    @Around("@annotation(deleteCache)")
    public Object deleteCache(ProceedingJoinPoint joinPoint, DeleteCache deleteCache) throws Throwable {
        Integer count = (int)joinPoint.proceed();
        if (count > 0) {
        redisTemplate.delete(deleteCache.key());
        }
        return count;
    }

}
